#include <nlohmann/json.hpp>
#include <fstream>
#include <mutex>
using json = nlohmann::json;
class ConfigManager {
public:
    static ConfigManager& getInstance() {
        static ConfigManager instance;
        return instance;
    }
    void load(const std::string& path) {
        std::lock_guard<std::mutex> lock(configMutex);
        std::ifstream configFile(path);
        if (!configFile.is_open()) {
            throw std::runtime_error("Config file not found: " + path);
        }
        config = json::parse(configFile);
        currentPath = path;
        Logger::log("Configuration loaded from " + path);
    }
    template<typename T>
    T get(const std::string& keyPath) {
        std::lock_guard<std::mutex> lock(configMutex);
        return config.value<T>(keyPath, T());
    }
    template<typename T>
    void set(const std::string& keyPath, const T& value) {
        std::lock_guard<std::mutex> lock(configMutex);
        json_ptr = &config;
        for (const auto& key : split(keyPath, '.')) {
            if (it == keyPath.end()) {
                *json_ptr = value;
                save();
                return;
            }
            json_ptr = &((*json_ptr)[key]);
        }
    }
    void save() {
        std::ofstream configFile(currentPath);
        configFile << config.dump(2);
        Logger::log("Configuration saved to " + currentPath);
    }
private:
    json config;
    std::string currentPath;
    std::mutex configMutex;
    ConfigManager() = default;
    ConfigManager(const ConfigManager&) = delete;
    void operator=(const ConfigManager&) = delete;
};